package com.xyx.yfy_site_msg.system.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.IdUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 文件上传下载工具类
 */
public class AppFileUtils {

    public static String UPLOAD_PATH = "D:/upload/";//默认值

    static {
//        读取配置文件的存储地址
        InputStream resourceAsStream = AppFileUtils.class.getClassLoader().getResourceAsStream("file.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String property = properties.getProperty("filepath");
        if (null != property) {
            UPLOAD_PATH = property;
        }
    }

    /**
     * 根据文件旧名字得到新的名字
     *
     * @param oldName
     * @return
     */
    public static String createNewFileName(String oldName) {
        String stuff = oldName.substring(oldName.lastIndexOf("."), oldName.length());
        return IdUtil.simpleUUID().toUpperCase() + stuff;
    }

    public static ResponseEntity<Object> createResponseEntity(String path) {
//        1、构造文件对象
        File file = new File(UPLOAD_PATH, path);
        if (file.exists()) {
//            2、将下载的文件，封装byte[]
            byte[] bytes = null;
            try {
                bytes = FileUtil.readBytes(file);
            } catch (IORuntimeException e) {
                e.printStackTrace();
                System.out.println("封装byte失败");
            }
//            3、创造封装响应头信息的对象
            HttpHeaders headers = new HttpHeaders();
//            封装响应内容类型【APPLICATION_OCTET_STREAM 响应的内容不限定】
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//            设置下载的文件的名称
//			header.setContentDispositionFormData("attachment", "123.jpg");
//            设置ResponseEntity对象
            ResponseEntity<Object> entity = new ResponseEntity<>(bytes, headers, HttpStatus.CREATED);
            return entity;
        }
        return null;
    }

    /**
     * 根据路径名字去掉后缀_temp
     *
     * @param getFile
     * @return
     */
    public static String renameFile(String getFile) {
        File file = new File(UPLOAD_PATH, getFile);
        String replace = getFile.replace("_temp", "");
        if (file.exists()) {
            file.renameTo(new File(UPLOAD_PATH, replace));
        }
        return replace;
    }


}
